# -*- coding: utf-8 -*-
import binascii
import importlib
import sys
from PySide6.QtCore import Signal, QTimer, Qt
from PySide6.QtGui import QShortcut, QKeySequence, QFontDatabase, QFont
from PySide6.QtWidgets import QWidget, QMessageBox, QApplication, QMainWindow, QTextBrowser
from loguru import logger

from plugins.fontTextUI_ui import Ui_FontTextWindow
from utils.bytesHelper import SliceBytesSafe
from utils.filePathTools import GetFilesWithExtension

import os


def GetFontFiles(directory, need_ext=False):
    """
    获取指定目录下所有常见字体文件（如 .ttf, .otf）的文件名列表。

    :param directory: 要搜索的目录路径
    :param need_ext: 是否保留文件扩展名，默认为 False
    :return: 包含匹配字体文件名的列表
    """
    # 常见字体文件扩展名
    font_extensions = {'.ttf', '.otf', '.woff', '.woff2'}

    # 确保目录存在
    if not os.path.exists(directory):
        return []

    # 获取目录下所有文件
    all_files = os.listdir(directory)

    # 使用列表推导式过滤具有常见字体后缀的文件
    if need_ext:
        filtered_files = [file for file in all_files if any(file.endswith(ext) for ext in font_extensions)]
    else:
        filtered_files = [os.path.splitext(file)[0] for file in all_files if
                          any(file.endswith(ext) for ext in font_extensions)]

    return filtered_files


class GWMC01IICWindow(QMainWindow, Ui_FontTextWindow):
    """
    字体显示
    """

    def __init__(self):
        super().__init__()
        # 加载UI
        self.setupUi(self)
        # 连接信号与槽
        self.SignalConnectInit()
        # 添加快捷键
        self.ShortcutFun()
        self.font_files = GetFontFiles('./', need_ext=True)
        print(self.font_files)
        self.statusbar.showMessage("wonvan 版权所有 盗因必究")

    def CleanupSelf(self):
        """
        清理当前窗口并关闭，由其他其他程序调用
        :return:
        """
        try:
            # 停止并注销定时器
            self.close()  # 关闭当前窗口
            self.deleteLater()  # 释放子窗口资源
            print("TpIntWindow.__del__.ok")
        except Exception as err:
            print("TpIntWindow.__del__.error", err)

    def SignalConnectInit(self):
        """
        连接来自UI对象的信号与槽
        :return:
        """
        self.textEdit.setPlaceholderText("输入文字内容...")
        self.textEdit.textChanged.connect(self.TextEditChangedFun)

    def update_font_displays(self, textBrowserObj: QTextBrowser, font_path):
        # 获取顶部输入框内容并更新所有字体展示栏
        text = self.textEdit.toPlainText()
        if font_path:
            # 加载字体并应用到展示框
            font_id = QFontDatabase.addApplicationFont(font_path)
            if font_id != -1:
                font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
                font = QFont(font_family, 12)
                textBrowserObj.setFont(font)
        textBrowserObj.setPlainText(text)

    def TextEditChangedFun(self):
        for item in range(1, 13):
            print(item, "<<<<<<<")
            if item < len(self.font_files):
                expr = f"self.update_font_displays(self.textBrowser{item}, '{self.font_files[item - 1]}')"
                exec(expr)
            else:
                expr = f"self.update_font_displays(self.textBrowser{item}, None)"
                exec(expr)

    def ShortcutFun(self):
        """
        快捷键 F11 全屏
        快捷键 F5 清屏
        :return:
        """
        # 快捷键 F11
        self.screenStatus = 'Normal'
        screenShortcut = QShortcut(QKeySequence(Qt.Key_F11), self)
        screenShortcut.activated.connect(self.WindowSizeFun)
        self.setToolTip('全屏与退出全屏：\n               双击 或者 F11')
        # 快捷键 F5
        # screenShortcut2 = QShortcut(QKeySequence(Qt.Key_F5), self)
        # screenShortcut2.activated.connect(self.CleanFun)

    def WindowSizeFun(self):
        """
        控制窗口尺寸，此处为原大小（最小UI布局）或者全屏
        :return:
        """
        if self.screenStatus == 'Normal':
            self.showFullScreen()
            self.screenStatus = 'FullScreen'
        else:
            self.showNormal()
            self.screenStatus = 'Normal'

    def closeEvent(self, event):
        """
        防止误触关闭程序
        :param event:
        :return:
        """
        # 创建一个确认退出的对话框
        reply = QMessageBox.question(
            self, "Confirmation", "Are you sure you want to exit?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No
        )
        if reply == QMessageBox.StandardButton.Yes:
            self.CleanupSelf()
            # 用户确认退出，关闭应用
            event.accept()
        else:
            event.ignore()


# 程序入口，测试当前插件文件使用
if __name__ == "__main__":
    app = QApplication(sys.argv)
    myWindow = GWMC01IICWindow()
    myWindow.show()
    sys.exit(app.exec())
